<template>
  <div :class="{'mobile-wrap':showMobilePage}" class="approval-module-container">
    <FilterInput
      ref="FilterToolRef"
      v-model="paramsObj"
      :filter-list="filterList"
      :show-advanced-filter="false"
      style="margin-bottom: 12px"
      show-search-btn
      @handelClick="queryClick"
      @queryEmpty="queryEmpty"/>
    <div v-loading="initLoading" v-if="!isInit" style="height: 300px" />
    <el-collapse v-loading="initLoading" v-else-if="getModulesLength" v-model="activeNames" style="min-height: 100px">
      <template v-for="module in modules">
        <el-collapse-item
          v-if="module.children && module.children.length"
          :key="module.name"
          :name="module.name">
          <div slot="title" class="module-group-name">
            <i :class="activeNames.includes(module.name) ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" />
            {{ module.name }}
            <span style="color: #999; font-weight: normal">({{ module.children && module.children.length || 0 }})</span>
          </div>
          <div class="module-group">
            <template v-for="item in module.children || []">
              <div v-if="!showMobilePage" :key="item.id" class="module-box" @click="goApprovalList(item)">
                <el-badge :value="item.myApprovalNum? item.myApprovalNum > 99? '99+' : item.myApprovalNum : ''" class="module-badge">
                  <div :style="{ background: item.iconColor || defaultColor }" class="module-icon">
                    <img :src="getIcon(item.icon)">
                  </div>
                </el-badge>
                <el-tooltip :open-delay="800" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px">
                    {{ item.name }}
                  </div>
                  <div class="module-name">{{ item.name }}</div>
                </el-tooltip>
              </div>
              <NavItem v-else :key="item.id" :my-approval-num="item.myApprovalNum" :background-color="item.iconColor" :name="item.name" :icon="getIcon(item.icon)" class="module-item" @click.native="goApprovalList(item)"/>
            </template>
          </div>
        </el-collapse-item>
      </template>
    </el-collapse>
    <EmptyPlaceholder v-loading="initLoading" v-else :empty-text-top="0" text="暂无数据" />
  </div>
</template>

<script>
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { getProcessManagement, getRecentlyUsedList } from '@/api/legal';
import { ROUTE_PARAMS, CONTRACT_TYPES } from '@/utils/const/process';
import { mapState } from 'vuex';
import iconConfig from '@/mixins/iconConfig';
import NavItem from '@/views/layout/components/navItem';
export default {
  name: 'ApprovalModule',
  components: {
    EmptyPlaceholder,
    NavItem
  },
  mixins: [iconConfig],
  data() {
    return {
      isInit: false,
      initLoading: false,
      paramsObj: {},
      activeNames: [],
      modules: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    filterList() {
      return [
        { keyword: 'name', name: '审批名称', type: 'input', placeholder: '请输入审批名称' }
      ];
    },
    getModulesLength() {
      if (!this.modules.length) return 0;
      return this.modules.reduce((pre, curr) => pre + (curr.children && curr.children.length ? 1 : 0), 0);
    }
  },
  created() {
    this.queryAllProcessManagement();
  },
  methods: {
    async queryAllProcessManagement() {
      this.initLoading = true;
      const params = _.cloneDeep(this.paramsObj);
      params.type = 1;
      let recentlyUsedList = [];
      try {
        if (!params.name) {
          recentlyUsedList = await this.getRecentlyUsedList();
          if (!Array.isArray(recentlyUsedList)) {
            recentlyUsedList = [];
          }
        }
        const processManagement = await this.queryProcessManagement(params);
        this.initLoading = false;
        this.isInit = true;
        this.modules = [...recentlyUsedList, ...processManagement];
      } catch (e) {
        this.initLoading = false;
      }
    },
    async queryProcessManagement(params) {
      try {
        const res = await getProcessManagement(params);
        const processManagement = this.setContractModules(res.data);
        processManagement.forEach(module => {
          this.activeNames.push(module.name);
        });
        return processManagement;
      } catch (e) {
        this.initLoading = false;
      }
    },
    // 最近使用
    async getRecentlyUsedList() {
      try {
        const res = await getRecentlyUsedList({ isMobile: false, pageSize: 8 });
        this.activeNames.unshift('最近使用');
        return [{ name: '最近使用', children: res.data }];
      } catch (e) {
        this.initLoading = false;
      }
    },
    // 将合同所有子类型合并成单个合同流程模块
    setContractModules(list) {
      if (!Array.isArray(list) || !list.length) return [];
      const contractModuleIndex = this.getContractModuleIndex(list);
      const contractProcess = { name: '合同审批', id: -1, icon: 'configIcon2', type: -1 };
      if (contractModuleIndex !== -1) {
        const contractModuleData = list[contractModuleIndex];
        const contractModuleList = contractModuleData.children || [];
        const result = contractModuleList.filter(module => !CONTRACT_TYPES.includes(module.type));
        const contractProcessList = contractModuleList.filter(module => CONTRACT_TYPES.includes(module.type)) || [];
        contractProcess.myApprovalNum = contractProcessList.length ? contractProcessList[0].myApprovalNum : 0;
        result.unshift(contractProcess);
        list[contractModuleIndex].children = result;
      }
      return list;
    },
    // 获取合同类所在分类
    getContractModuleIndex(list) {
      let findIndex = -1;
      list.forEach((item, index) => {
        item.children && item.children.forEach(module => {
          if (CONTRACT_TYPES.includes(module.type)) {
            findIndex = index;
          }
        });
      });
      return findIndex;
    },
    queryClick() {
      this.queryAllProcessManagement();
    },
    queryEmpty() {
      this.paramsObj = {};
      this.queryAllProcessManagement();
    },
    goApprovalList(data) {
      if (data.isCustom) {
        this.$router.push({
          name: 'approvalList',
          params: { id: data.id },
          query: { isFromApprovalModule: 1 }
        });
      } else {
        if (ROUTE_PARAMS.has(data.type)) {
          const routeName = ROUTE_PARAMS.get(data.type);
          this.$router.push({ name: routeName });
        } else {
          this.$message.warning('无法识别此流程模块');
        }
      }
    }
  }
};
</script>

<style scoped lang="scss">
.approval-module-container {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 24px;
  min-height: calc(100vh - 80PX);
  &::v-deep {
    .el-collapse, .el-collapse-item__header, .el-collapse-item__wrap {
      border: none;
    }
    .el-collapse-item__header {
      height: 32px;
    }
    .el-collapse-item__arrow {
      display: none;
    }
    .el-collapse-item__content {
      padding: 0 0 0 20px !important;
    }
  }
  .module-group-name {
    font-size: 14px;
    font-weight: bold;
    user-select: none;
    ::v-deep .el-icon-arrow-down:before {
      color: #AEB6C7
    }
  }
  .module-group {
    display: flex;
    flex-wrap: wrap;
    margin-right: -12px;
    .module-box {
      margin: 0 12px 12px 0;
      padding: 12px;
      display: flex;
      align-items: center;
      width: 180px;
      height: 56px;
      border: 1px solid #EBEEFD;
      border-radius: 4px;
      cursor: pointer;
      &:hover {
        background-color: #f0f4ff;
        color: #406eff;
        border-color: #406eff;
      }
      .module-badge {
        ::v-deep .el-badge__content {
          display: flex;
          align-items: center;
          right: 18px;
          border: 2px solid #fff;
          background: #FB5227;
        }
      }
      .module-icon {
        width: 32px;
        height: 32px;
        margin-right: 8px;
        background-color: transparent;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;
        > img {
          width: 20px;
          height: 20px;
        }
      }
      .module-name {
        font-size: 14px;
        line-height: 1.4;
        flex: 1;
        -webkit-box-orient: vertical;
        display: -webkit-box;
        overflow: hidden;
        -webkit-line-clamp: 2;
        text-overflow: ellipsis;
      }
    }
  }
}
.mobile-wrap {
  margin: 0px;
  padding: 12px;
  border-radius: 0px;
  &::v-deep {
    .el-input__inner {
      width: 100% !important;
    }
    .high-lv {
      color: #406eff !important;
    }
    .el-collapse-item__content {
      padding: 0 !important;
    }
  }
  .module-item {
    margin:0 6px 0px 0!important;
  }
}
</style>
